package com.sky.service.Impl;

import com.sky.context.BaseContext;
import com.sky.dao.SetDefaultDTO;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressBookImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBook> list() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list = addressBookMapper.list(addressBook);
        return list;
    }

    @Override
    public AddressBook defaultAddress() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault((short) 1);
        List<AddressBook> list = addressBookMapper.list(addressBook);
        addressBook = list.get(0);
        return addressBook;
    }

    @Override
    public AddressBook getById(Long id) {
        AddressBook addressBook = new AddressBook();
        addressBook.setId(id);
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list = addressBookMapper.list(addressBook);
        addressBook = list.get(0);
        return addressBook;
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.update(addressBook);
    }

    @Override
    public void save(AddressBook addressBook) {
        addressBook.setIsDefault((short) 0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.save(addressBook);
    }

   @Transactional
    public void setDefault(SetDefaultDTO setDefaultDTO) {
        AddressBook addressBook = defaultAddress();
        addressBook.setIsDefault((short) 0);
        addressBookMapper.update(addressBook);

        AddressBook addressBook1 = new AddressBook();
        addressBook1.setId(setDefaultDTO.getId());
        addressBook1.setIsDefault((short) 1);
        addressBookMapper.update(addressBook1);

    }

    @Override
    public void delete(Long id) {
        addressBookMapper.delete(id);
    }
}
